package com.example.demogateway.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.common.entitys.AuthUserDetails;
import com.example.demogateway.cache.CacheUtils;
import com.example.demogateway.utils.RestResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.WebFilterChainServerAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.List;

@Component
public class AuthenticationSuccessHandler extends WebFilterChainServerAuthenticationSuccessHandler {
    private static final Logger logger = LoggerFactory.getLogger(AuthenticationSuccessHandler.class);
    @Override
    public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
        ServerWebExchange exchange = webFilterExchange.getExchange();
        ServerHttpResponse response = exchange.getResponse();
        //设置headers
        HttpHeaders httpHeaders = response.getHeaders();
        httpHeaders.add("Content-Type", "application/json; charset=UTF-8");
        httpHeaders.add("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
        //设置body
        RestResponse wsResponse = RestResponse.success(null);
        byte[] dataBytes = {};
        ObjectMapper mapper = new ObjectMapper();
        User user =  null;
        try {
            user = (User) authentication.getPrincipal();
           String orgpassword = user.getPassword();
            AuthUserDetails userDetails = buildUser(user);
            byte[] authorization = (userDetails.getUsername() + ":" + userDetails.getPassword()).getBytes();
            String token = Base64.getEncoder().encodeToString(authorization);
            //将授权信息放到头部
            httpHeaders.add(HttpHeaders.AUTHORIZATION, token);
            //放入缓存中
            CacheUtils.put(token,JSON.toJSONString(userDetails));

            JSONObject tokenObj = new JSONObject();
            tokenObj.put("token",token);
            tokenObj.put("expires_in",7200);//凭证有效时间，单位：秒

            //将用户信息放到返回信息题里面
            wsResponse.setData(tokenObj);
            dataBytes = mapper.writeValueAsBytes(wsResponse);

        } catch (Exception ex) {

            logger.error("登录异常,user="+ JSON.toJSONString(user),ex);

            RestResponse response1 = RestResponse.build(401,"授权异常");
            dataBytes = JSON.toJSONString(response1).getBytes();
        }
        DataBuffer bodyDataBuffer = response.bufferFactory().wrap(dataBytes);
        return response.writeWith(Mono.just(bodyDataBuffer));
    }


    private AuthUserDetails buildUser(User user) {
        AuthUserDetails userDetails = new AuthUserDetails();
        userDetails.setUsername(user.getUsername());
        userDetails.setPassword(user.getPassword().substring(user.getPassword().lastIndexOf("}") + 1, user.getPassword().length()));
        Collection<GrantedAuthority> grantedAuthorityList = user.getAuthorities();
        if(grantedAuthorityList != null){
            List permsList = new ArrayList();
            for (GrantedAuthority grantedAuthority : grantedAuthorityList) {
                permsList.add(grantedAuthority.getAuthority());
            }
            userDetails.setPermsList(permsList);
        }
        return userDetails;
    }
}

